package com.ruizhong.integratedmediawithoutc.config;

import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.resource.PathResourceResolver;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

public class DynamicAssetsResourceResolver extends PathResourceResolver {
    
    // 资源路径提供者接口
    public interface AssetsPathProvider {
        String getCurrentAssetsPath();
    }
    
    private final AssetsPathProvider pathProvider;
    
    public DynamicAssetsResourceResolver(AssetsPathProvider pathProvider) {
        this.pathProvider = pathProvider;
    }
    
    @Override
    protected Resource getResource(String resourcePath, Resource location) throws IOException {
        // 解码URL中的中文和特殊字符
        String decodedPath;
        try {
            decodedPath = URLDecoder.decode(resourcePath, StandardCharsets.UTF_8.name());
        } catch (UnsupportedEncodingException e) {
            decodedPath = resourcePath;
        }

        // 处理Windows文件系统路径
        decodedPath = decodedPath.replace('/', File.separatorChar);

        // 获取动态路径
        String currentAssetsPath = pathProvider.getCurrentAssetsPath();
        File resourceFile = new File(currentAssetsPath, decodedPath);

        // 验证文件是否存在且可读
        if (resourceFile.exists() && resourceFile.canRead()) {
            return new FileSystemResource(resourceFile);
        }

        return null;
    }
}